<template>
	<view class="after-sale-detail-container page-container">
		<!-- 状态卡片 -->
		<view class="status-card">
			<view class="status-icon">
				<text class="icon-text">{{ getStatusIcon(afterSaleInfo.after_sale_status) }}</text>
			</view>
			<view class="status-content">
				<text class="status-title">{{ getStatusTitle(afterSaleInfo.after_sale_status) }}</text>
				<text class="status-desc">{{ getStatusDesc(afterSaleInfo.after_sale_status) }}</text>
			</view>
		</view>

		<!-- 售后信息 -->
		<view class="info-section">
			<view class="section-title">
				<text class="title-text">售后信息</text>
			</view>
			<view class="info-card">
				<view class="info-row">
					<text class="info-label">售后单号</text>
					<text class="info-value">{{ afterSaleInfo.after_sale_sn }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">关联订单</text>
					<text class="info-value">S{{ afterSaleInfo.order_id }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">售后类型</text>
					<text class="info-value">{{ getTypeTitle(afterSaleInfo.after_sale_type) }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">申请时间</text>
					<text class="info-value">{{ afterSaleInfo.apply_time }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">售后金额</text>
					<text class="info-value amount">¥{{ afterSaleInfo.refund_total_amount }}</text>
				</view>
			</view>
		</view>

		<!-- 客户信息 -->
		<view class="customer-section">
			<view class="section-title">
				<text class="title-text">客户信息</text>
			</view>
			<view class="customer-card">
				<view class="customer-row">
					<text class="customer-label">客户姓名</text>
					<text class="customer-value">{{ afterSaleInfo.contactName }}</text>
				</view>
				<view class="customer-row">
					<text class="customer-label">联系电话</text>
					<text class="customer-value">{{ afterSaleInfo.contactPhone }}</text>
					<button class="call-btn" @click="callCustomer">拨打</button>
				</view>
			</view>
		</view>

		<!-- 商品信息 -->
		<view class="product-section">
			<view class="section-title">
				<text class="title-text">商品信息</text>
			</view>
			<view class="product-card" v-for="product in afterSaleInfo.sku_info" :key="product.id">
				<image :src="$tools.buildUrl(product.main_image)" mode="aspectFill" class="product-image"></image>
				<view class="product-details">
					<text class="product-name">{{ product.spu_name }}</text>
					<text class="product-spec">{{ product.sku_name }}</text>
					<view class="product-price-row">
						<text class="product-price">¥{{ product.actual_price }}</text>
						<text class="product-quantity">x{{ product.quantity }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 申请详情 -->
		<view class="detail-section">
			<view class="section-title">
				<text class="title-text">申请详情</text>
			</view>
			<view class="detail-card">
				<view class="detail-row">
					<text class="detail-label">申请原因</text>
					<text class="detail-value">{{ afterSaleInfo.reason }}</text>
				</view>
				<view class="detail-row">
					<text class="detail-label">问题描述</text>
					<text class="detail-value">{{ afterSaleInfo.reason_remark }}</text>
				</view>
				<view class="detail-row" v-if="afterSaleInfo.evidence && afterSaleInfo.evidence.length > 0">
					<text class="detail-label">问题图片</text>
					<view class="image-list">
						<image v-for="(image, index) in afterSaleInfo.evidence" :key="index"
							:src="$tools.buildUrl(image)" mode="aspectFill" class="problem-image"
							@click="previewImage(image, afterSaleInfo.evidence)">
						</image>
					</view>
				</view>
			</view>
		</view>

		<!-- 审核信息 -->
		<view class="audit-section" v-if="afterSaleInfo.check_status > 0">
			<view class="section-title">
				<text class="title-text">审核信息</text>
			</view>
			<view class="audit-card">
				<view class="audit-row">
					<text class="audit-label">审核结果</text>
					<text class="audit-value"
						:class="'result-' + ([1,3].includes(afterSaleInfo.check_status)? 'approved' : 'reject')">
						{{ [1,3].includes(afterSaleInfo.check_status) ? '同意' : '拒绝' }}
					</text>
				</view>
				<view class="audit-row">
					<text class="audit-label">审核时间</text>
					<text class="audit-value">{{ afterSaleInfo.check_time }}</text>
				</view>
				<view class="audit-row" v-if="afterSaleInfo.chack_reason">
					<text class="audit-label">审核备注</text>
					<text class="audit-value">{{ afterSaleInfo.chack_reason }}</text>
				</view>
			</view>
		</view>

		<!-- 退货地址信息 -->
		<view class="address-section"
			v-if="afterSaleInfo.after_sale_status >0 && [1,2].includes(afterSaleInfo.after_sale_type)">
			<view class="section-title">
				<text class="title-text">退货地址</text>
			</view>
			<view class="address-card">
				<view class="address-row">
					<text class="address-label">收货人</text>
					<text class="address-value">{{ afterSaleInfo.return_name }}</text>
				</view>
				<view class="address-row">
					<text class="address-label">联系电话</text>
					<text class="address-value">{{ afterSaleInfo.return_phone }}</text>
				</view>
				<view class="address-row">
					<text class="address-label">退货地址</text>
					<text class="address-value">{{ afterSaleInfo.return_pcs+' '+afterSaleInfo.return_address }}</text>
				</view>
				<view class="address-row">
					<text class="address-label">邮政编码</text>
					<text class="address-value">{{ afterSaleInfo.return_zipCode }}</text>
				</view>
			</view>
		</view>

		<!-- 操作按钮 -->
		<view class="action-section" v-if="afterSaleInfo.after_sale_status === 0">
			<button class="action-btn approve-btn" @click="approveAfterSale">同意申请</button>
			<button class="action-btn reject-btn" @click="rejectAfterSale">拒绝申请</button>
		</view>
		<view class="action-section" v-else>
			<!-- 商家签收退货商品 -->
			<button v-if="canReceive" class="action-btn approve-btn" @click="receiveAfterSale">确认签收</button>
			<!-- 商家同意仅退款 / 商家已签收退货商品 -->
			<button v-if="canRefund" class="action-btn reject-btn" @click="refundAfterSale">确认退款</button>
		</view>

		<!-- 审核弹窗 -->
		<u-popup :show="showAuditPopup" @close="closeAuditPopup" mode="center" border-radius="20">
			<view class="audit-popup">
				<view class="popup-header">
					<text class="popup-title">{{ auditType === 'approve' ? '同意售后' : '拒绝售后' }}</text>
				</view>
				<view class="popup-content">
					<view class="form-item">
						<text class="form-label">审核备注</text>
						<textarea class="form-textarea"
							:placeholder="auditType === 'approve' ? '请输入同意原因（可选）' : '请输入拒绝原因'" v-model="auditRemark"
							maxlength="200"></textarea>
					</view>
				</view>
				<view class="popup-actions">
					<button class="cancel-btn" @click="closeAuditPopup">取消</button>
					<button class="confirm-btn" @click="confirmAudit">确认</button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				afterSaleId: '',
				showAuditPopup: false,
				auditType: '', // 'approve' 或 'reject'
				auditRemark: '',
				afterSaleInfo: {}
			}
		},

		computed: {
			// 是否可以确认收货
			canReceive() {
				return this.afterSaleInfo.after_sale_status === 5
			},
			// 是否可以确认退款
			canRefund() {
				const yes = this.afterSaleInfo.after_sale_status === 7 && this.afterSaleInfo.after_sale_type === 1;
				const yes2 = this.afterSaleInfo.after_sale_status === 1 && this.afterSaleInfo.after_sale_type === 3;
				return yes || yes2
			}
		},

		onLoad(options) {
			if (options.id) {
				this.afterSaleId = options.id
				this.loadAfterSaleDetail()
			}
		},

		methods: {
			onSearch() {
				if (this.afterSaleId) {
					this.loadAfterSaleDetail()
				}
			},
			// 加载售后详情
			loadAfterSaleDetail(refresh) {
				this.$api.order.GetAfterSalesInfo({
					id: this.afterSaleId
				}).then(res => {
					res.data.sku_info = this.$tools.parseJsonObject(res.data.sku_info)
					res.data.evidence = this.$tools.parseJsonObject(res.data.evidence)
					const province = this.$tools.parseJsonObject(res.data.return_province)
					const city = this.$tools.parseJsonObject(res.data.return_city)
					const town = this.$tools.parseJsonObject(res.data.return_town)
					if (province && province.name) {
						res.data.return_pcs = province.name + city.name + town.name;
					} else {
						res.data.return_pcs = '';
					}
					this.afterSaleInfo = res.data;

					// 更新列表页售后单状态
					if (refresh) {
						const pages = getCurrentPages()
						const prevPage = pages[pages.length - 2]
						if (prevPage) {
							prevPage.$vm.setOrderStatus(this.afterSaleInfo)
						}
					}
				})
			},

			// 获取状态图标
			getStatusIcon(status) {
				const iconMap = {
					0: '⏳',
					1: '✅',
					2: '❌',
					3: '⏳',
					4: '⏳',
					5: '⏳',
					6: '⏳',
					7: '⏳',
					8: '⏳',
					9: '🎉',
					10: '❌',
					11: '❌'
				}
				return iconMap[status] || '❓'
			},

			getTypeTitle(type) {
				const titleMap = {
					1: '退货',
					2: '换货',
					3: '仅退款',
					4: '补寄'
				}
				return titleMap[type] || '未知'
			},

			// 获取状态标题
			getStatusTitle(status) {
				const titleMap = {
					0: '商家审核中',
					1: '商家已同意',
					2: '商家已拒绝',
					3: '待用户发货',
					4: '待商家发货',
					5: '用户已发货,待商家收货',
					6: '商家已发货,待用户收货',
					7: '商家已签收',
					8: '用户已签收',
					9: '售后已完成',
					10: '售后失败',
					11: '用户取消售后'
				}
				return titleMap[status] || '未知状态'
			},

			// 获取状态描述
			getStatusDesc(status) {
				const descMap = {
					0: '客户已提交售后申请，请及时审核处理',
					1: '售后申请已通过审核',
					2: '售后申请已被拒绝，客户可查看拒绝原因',
					3: '售后申请已通过审核，客户可按指引进行退货',
					4: '售后申请已通过审核，请耐心等待商家发货',
					5: '售后商品已经寄出，等待商家签收',
					6: '商家已发货,请耐心等待',
					7: '商家已签收',
					8: '用户已签收',
					9: '售后处理已完成',
					10: '售后失败',
					11: '用户已经取消'
				}
				return descMap[status] || '状态未知'
			},

			// 拨打客户电话
			callCustomer() {
				uni.makePhoneCall({
					phoneNumber: this.afterSaleInfo.contactPhone.replace(/\*/g, ''),
					fail: () => {
						uni.showToast({
							title: '拨打失败',
							icon: 'none'
						})
					}
				})
			},

			// 预览图片
			previewImage(current, urls) {
				let newUrls = []
				urls.forEach(image => {
					newUrls.push(this.$tools.buildUrl(image))
				})
				uni.previewImage({
					current: this.$tools.buildUrl(current),
					urls: newUrls
				})
			},

			// 同意售后
			approveAfterSale() {
				this.auditType = 'approve'
				this.auditRemark = ''
				this.showAuditPopup = true
			},

			// 拒绝售后
			rejectAfterSale() {
				this.auditType = 'reject'
				this.auditRemark = ''
				this.showAuditPopup = true
			},

			// 关闭审核弹窗
			closeAuditPopup() {
				this.showAuditPopup = false
				this.auditRemark = ''
			},

			// 确认审核
			confirmAudit() {
				if (this.auditType === 'reject' && !this.auditRemark.trim()) {
					uni.showToast({
						title: '请输入拒绝原因',
						icon: 'none'
					})
					return
				}

				uni.showLoading({
					title: '处理中...'
				})

				this.$api.agent.AfterSalesCheck({
					id: this.afterSaleId,
					check_status: this.auditType === 'reject' ? 2 : 1,
					chack_reason: this.auditRemark,
				}).then(res => {
					uni.hideLoading()

					// 更新售后状态
					res.data.sku_info = this.$tools.parseJsonObject(res.data.sku_info)
					res.data.evidence = this.$tools.parseJsonObject(res.data.evidence)
					const province = this.$tools.parseJsonObject(res.data.return_province)
					const city = this.$tools.parseJsonObject(res.data.return_city)
					const town = this.$tools.parseJsonObject(res.data.return_town)
					if (province && province.name) {
						res.data.return_pcs = province.name + city.name + town.name;
					} else {
						res.data.return_pcs = '';
					}
					this.afterSaleInfo = res.data

					// 更新列表数据					
					const pages = getCurrentPages()
					const prevPage = pages[pages.length - 2]
					if (prevPage) {
						prevPage.$vm.setOrderStatus(this.afterSaleInfo)
					}

					this.closeAuditPopup()
					uni.showToast({
						title: this.auditType === 'approve' ? '已同意售后申请' : '已拒绝售后申请',
						icon: 'success'
					})
				})
			},

			// 商家确认签收
			receiveAfterSale() {
				if (!this.canReceive) {
					return
				}

				uni.showModal({
					title: '确认签收',
					content: '确认已签收退货商品吗？',
					success: (res) => {
						if (res.confirm) {
							this.$api.agent.AfterSalesReceive({
								id: this.afterSaleInfo.id,
							}).then(res => {
								uni.showToast({
									title: res.msg,
									icon: 'success'
								})

								res.data.sku_info = this.$tools.parseJsonObject(res.data.sku_info)
								res.data.evidence = this.$tools.parseJsonObject(res.data.evidence)
								const province = this.$tools.parseJsonObject(res.data.return_province)
								const city = this.$tools.parseJsonObject(res.data.return_city)
								const town = this.$tools.parseJsonObject(res.data.return_town)
								if (province && province.name) {
									res.data.return_pcs = province.name + city.name + town.name;
								} else {
									res.data.return_pcs = '';
								}
								this.afterSaleInfo = res.data

								const pages = getCurrentPages()
								const prevPage = pages[pages.length - 2]
								if (prevPage) {
									prevPage.$vm.setOrderStatus(this.afterSaleInfo)
								}
							})
						}
					}
				})
			},

			// 商家确认退款
			refundAfterSale() {
				if (!this.canRefund) {
					return
				}

				uni.showModal({
					title: '确认退款',
					content: '确认全额退款 ￥' + this.afterSaleInfo.refund_total_amount + ' 吗？',
					success: (res) => {
						if (res.confirm) {
							this.$api.agent.AfterSalesRefund({
								id: this.afterSaleInfo.id,
								real_refund_amount: this.afterSaleInfo.refund_total_amount,
							}).then(res => {
								uni.showToast({
									title: res.msg,
									icon: 'success'
								})
								this.loadAfterSaleDetail(true)
							})
						}
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.after-sale-detail-container {
		background-color: #f8f9fa;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	}

	/* 状态卡片 */
	.status-card {
		display: flex;
		align-items: center;
		background-color: white;
		margin: 20rpx;
		padding: 40rpx 30rpx;
		border-radius: 16rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
	}

	.status-icon {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background-color: #f0f8ff;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 30rpx;
	}

	.icon-text {
		font-size: 40rpx;
	}

	.status-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.status-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.status-desc {
		font-size: 26rpx;
		color: #666;
		line-height: 1.4;
	}

	/* 通用区域样式 */
	.info-section,
	.customer-section,
	.product-section,
	.detail-section,
	.audit-section,
	.address-section {
		margin: 0 20rpx 20rpx;
	}

	.section-title {
		margin-bottom: 16rpx;
	}

	.title-text {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
	}

	/* 信息卡片 */
	.info-card,
	.customer-card,
	.detail-card,
	.audit-card,
	.address-card {
		background-color: white;
		border-radius: 16rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
	}

	.info-row,
	.customer-row,
	.detail-row,
	.audit-row,
	.address-row {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		margin-bottom: 24rpx;
	}

	.info-row:last-child,
	.customer-row:last-child,
	.detail-row:last-child,
	.audit-row:last-child,
	.address-row:last-child {
		margin-bottom: 0;
	}

	.info-label,
	.customer-label,
	.detail-label,
	.audit-label,
	.address-label {
		font-size: 26rpx;
		color: #666;
		width: 160rpx;
		flex-shrink: 0;
	}

	.info-value,
	.customer-value,
	.detail-value,
	.audit-value,
	.address-value {
		font-size: 26rpx;
		color: #333;
		flex: 1;
		text-align: right;
		word-break: break-all;
	}

	.amount {
		color: #52a58a;
		font-weight: bold;
	}

	/* 客户信息特殊样式 */
	.call-btn {
		margin-left: 20rpx;
		padding: 8rpx 20rpx;
		background-color: #52a58a;
		color: white;
		border: none;
		border-radius: 20rpx;
		font-size: 24rpx;
	}

	/* 商品信息 */
	.product-card {
		background-color: white;
		border-radius: 16rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.product-image {
		width: 120rpx;
		height: 120rpx;
		border-radius: 12rpx;
	}

	.product-details {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.product-name {
		font-size: 28rpx;
		color: #333;
		font-weight: bold;
	}

	.product-spec {
		font-size: 24rpx;
		color: #999;
	}

	.product-price-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.product-price {
		font-size: 28rpx;
		color: #52a58a;
		font-weight: bold;
	}

	.product-quantity {
		font-size: 26rpx;
		color: #666;
	}

	/* 图片列表 */
	.image-list {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
		margin-top: 16rpx;
	}

	.problem-image {
		width: 120rpx;
		height: 120rpx;
		border-radius: 12rpx;
	}

	/* 审核结果 */
	.result-approved {
		color: #52a58a;
		font-weight: bold;
	}

	.result-rejected {
		color: #ff4757;
		font-weight: bold;
	}

	/* 操作按钮 */
	.action-section {
		display: flex;
		gap: 20rpx;
		padding: 30rpx 20rpx;
	}

	.action-btn {
		flex: 1;
		padding: 0 24rpx;
		border-radius: 25rpx;
		font-size: 28rpx;
		font-weight: bold;
		border: none;
	}

	.approve-btn {
		background-color: #52a58a;
		color: white;
	}

	.reject-btn {
		background-color: #ff4757;
		color: white;
	}

	/* 审核弹窗 */
	.audit-popup {
		width: 600rpx;
		background-color: white;
		border-radius: 20rpx;
		overflow: hidden;
	}

	.popup-header {
		padding: 40rpx 30rpx 20rpx;
		text-align: center;
		border-bottom: 2rpx solid #f0f0f0;
	}

	.popup-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.popup-content {
		padding: 30rpx;
	}

	.form-item {
		margin-bottom: 30rpx;
	}

	.form-label {
		display: block;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 16rpx;
	}

	.form-textarea {
		width: 100%;
		min-height: 200rpx;
		padding: 20rpx;
		border: 2rpx solid #e9ecef;
		border-radius: 12rpx;
		font-size: 26rpx;
		color: #333;
		background-color: #f8f9fa;
	}

	.popup-actions {
		display: flex;
		border-top: 2rpx solid #f0f0f0;
	}

	.cancel-btn,
	.confirm-btn {
		flex: 1;
		padding: 30rpx;
		font-size: 28rpx;
		border: none;
		background-color: transparent;
	}

	.cancel-btn {
		color: #999;
	}

	.confirm-btn {
		color: #52a58a;
		font-weight: bold;
		border-left: 2rpx solid #f0f0f0;
	}
</style>